import { eq } from 'drizzle-orm'
import { rolesTable } from '~~/server/db/schema/role'
import { db } from '~~/server/db'

export default defineEventHandler(async (event) => {
  const id = Number(getRouterParam(event, 'id'))

  if (!id || isNaN(id)) {
    throw createError({
      statusCode: 400,
      message: '角色ID格式错误'
    })
  }

  try {
    const [user] = await db
      .select({
        id: rolesTable.id,
        name: rolesTable.name,
        value: rolesTable.value,
        remark: rolesTable.remark,
        createdAt: rolesTable.createdAt,
        updatedAt: rolesTable.updatedAt
      })
      .from(rolesTable)
      .where(eq(rolesTable.id, id))
      .limit(1)

    if (!user) {
      throw createError({
        statusCode: 404,
        message: '角色不存在'
      })
    }
    setResponseStatus(event, 200)
    return {
      data: user
    }
  } catch (error: any) {
    if (error.statusCode === 404) {
      throw error
    }
    console.error('Get user detail error:', error)
    throw createError({
      statusCode: 500,
      message: '获取角色详情失败'
    })
  }
})
